package me.zhengjie.modules.website.service.impl;

import me.zhengjie.modules.website.domain.Topics;
import me.zhengjie.modules.website.repository.TopicsRepository;
import me.zhengjie.modules.website.repository.TopicsSpecifications;
import me.zhengjie.modules.website.service.TopicsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import me.zhengjie.modules.website.domain.PageResult;

import java.util.List;

/**
 * @author system
 * @since 2024-12-02 17:12:28
 */
@Service
public class TopicsServiceImpl implements TopicsService {

    @Autowired
    private TopicsRepository topicsRepository;

    @Override
    public PageResult<Topics> findPage(Topics topics, Pageable pageable) {
        // 创建带排序的 Pageable
        Pageable sortedPageable = PageRequest.of(
                pageable.getPageNumber(),
                pageable.getPageSize(),
                Sort.by(Sort.Direction.ASC, "sortOrder")
        );

        // 使用带排序的 Pageable 进行查询
        Page<Topics> page = topicsRepository.findAll(TopicsSpecifications.queryList(topics), sortedPageable);

        // 构建分页结果
        PageResult<Topics> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }



    @Override
    public List<Topics> findList(Topics topics) {
        return topicsRepository.findAll(
                TopicsSpecifications.queryList(topics),
                Sort.by(Sort.Direction.DESC, "updateTime") // 按 update_time 降序排序
        );
    }


    @Override
    public Topics findById(Long id) {
        return topicsRepository.findById(id).orElse(null);
    }

    @Override
    public Topics insert(Topics topics) {
        return topicsRepository.save(topics);
    }

    @Override
    public Topics update(Topics topics) {
        return topicsRepository.saveAndFlush(topics);
    }

    @Override
    public void delete(Long id) {
        topicsRepository.deleteById(id);
    }

}